<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeGridProps } from '#/adapter/vxe-table'
import TableAction from '#/components/TableAction/index.vue'
import { useLocales } from '#/hooks/useLocales'
import { usePagePermission } from '#/hooks/usePermission'
import { useTableCURD } from '#/hooks/useTableList'
import { Page } from '@vben/common-ui'
import { $t } from '@vben/locales'
import AddEditModal from './components/AddEditModal.vue'
import { columns, formSchema } from './data/table'
import type { TableListItem } from './use/api'
import { PageApi } from './use/api'
import { PAGE_AUTH_CODE_PREFIX } from './use/config'

const { isLocaleZH } = useLocales()

const formOptions: VbenFormProps = {
    schema: formSchema,
    commonConfig: {
        labelWidth: isLocaleZH.value ? 100 : 150
    }
}

const gridOptions: VxeGridProps<any> = {
    columns,
    proxyConfig: {
        ajax: {
            query: async ({ page }, formValues) => {
                const res = await PageApi.getPageList({
                    ...formValues,
                    limit: page.pageSize,
                    page: page.currentPage
                })
                return {
                    items: res.records,
                    total: res.total
                }
            }
        }
    }
}

/**
 * 表格配置
 */
const {
    Grid,
    FormModal,
    viewDetail: handleViewDetail,
    handleSuccess,
    modalType
} = useTableCURD<TableListItem>({
    formOptions,
    gridOptions,
    modalOptions: {
        connectedComponent: AddEditModal
    },
    modalType: 'drawer'
})

// 权限配置
const { getPagePermissionKey } = usePagePermission(PAGE_AUTH_CODE_PREFIX)

/**
 * table 操作
 * @param record
 */
function getActions(record: TableListItem) {
    const arr: any[] = [
        {
            icon: 'ant-design:eye-outlined',
            tooltip: $t('common.details'),
            onClick: () => {
                handleViewDetail(record)
            },
            auth: getPagePermissionKey('index')
        }
    ]

    return arr
}
</script>

<template>
    <Page auto-content-height>
        <Grid>
            <template #action="{ row }">
                <TableAction :actions="getActions(row)" />
            </template>
        </Grid>
        <FormModal @success="handleSuccess" :modal-type="modalType" />
    </Page>
</template>
